﻿namespace MedicalPCTerminal.Write.API.Common
{
    /// <summary>
    /// 身份服务实现，用于获取当前用户信息
    /// </summary>
    public class IdentityService : IIdentityService
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContextAccessor">HTTP上下文访问器</param>
        public IdentityService(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
            
            // 添加空检查
            if (httpContextAccessor.HttpContext != null && 
                httpContextAccessor.HttpContext.User != null)
            {
                var userIdClaim = httpContextAccessor.HttpContext.User.FindFirst("UserId");
                var userNameClaim = httpContextAccessor.HttpContext.User.FindFirst("UserName");
                
                this.UserId = userIdClaim?.Value ?? string.Empty;
                this.UserName = userNameClaim?.Value ?? string.Empty;
            }
            else
            {
                this.UserId = string.Empty;
                this.UserName = string.Empty;
            }
        }

        /// <summary>
        /// 当前用户ID
        /// </summary>
        public string UserId { get; set; }
        
        /// <summary>
        /// 当前用户名
        /// </summary>
        public string UserName { get; set; }
    }

    /// <summary>
    /// 身份服务接口
    /// </summary>
    public interface IIdentityService
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public string UserId { get; set; }
        
        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName { get; set; }
    }
}
